const axios = require('axios');
const crypto = require('crypto');
const uuid = require('uuid');

const YOUDAO_URL = 'https://openapi.youdao.com/v2/api';
const APP_KEY = '47914f736192fb7c';
const APP_SECRET = '8xvcmYnXddtFX2uU6Zjurd77p9NfJ8IP';

async function connect() {
  const qArray = ["待输入的文字1", "待输入的文字2", "待输入的文字3"];

  const data = {};
  data.from = '源语言';
  data.to = '目标语言';
  data.signType = 'v3';
  const curtime = Math.floor(Date.now() / 1000);
  data.curtime = curtime.toString();
  const salt = uuid.v1().toString();
  const signStr = `${APP_KEY}${truncate(qArray.join(''))}${salt}${curtime}${APP_SECRET}`;
  const sign = encrypt(signStr);
  data.appKey = APP_KEY;
  data.salt = salt;
  data.q = qArray;
  data.sign = sign;
  data.vocabId = "您的用户词表ID";

  try {
    const response = await doRequest(data);
    console.log(response.headers['content-type']);
    console.log(response.data);
  } catch (error) {
    console.error('Error:', error);
  }
}

function encrypt(signStr) {
  return crypto.createHash('sha256').update(signStr).digest('hex');
}

function truncate(q) {
  if (q === null) {
    return null;
  }
  const qUtf8 = q;
  const size = qUtf8.length;
  return size <= 20 ? qUtf8 : qUtf8.substring(0, 10) + size + qUtf8.substring(size - 10, size);
}

async function doRequest(data) {
  return axios.get(YOUDAO_URL, { params: data });
}

connect();